package com.xiaoyu.im.request.flow;

import android.util.Log;

import com.xiaoyu.im.IMLog;
import com.xiaoyu.im.datamodel.AppMessage;
import com.xiaoyu.im.datamodel.MessageStatus;
import com.xiaoyu.im.datamodel.exception.IMException;
import com.xiaoyu.im.provider.MessageStatusProcessor;
import com.xiaoyu.im.request.MessageRequest;

public class BaseFailureAction implements FlowAction {

    @Override
    public void exec(MessageRequest request) {
        onFailure(request);
        logEvent(request);
    }

    protected void onFailure(MessageRequest request) {
        MessageStatusProcessor.getInstance().removeSending(request.getLocalId());
    }

    public void logEvent(MessageRequest request) {
        final AppMessage pendingMessage = request.getPendingMessage();
        final Throwable throwable = request.getThrowable();

        String throwableDesc = throwable == null ? "" : String.format(", error=%s, detail=%s", throwable.getMessage(), Log.getStackTraceString(throwable));
        String desc = String.format("chatId=%s, status=%s", pendingMessage.chatToken.getChatId(), MessageStatus.toString(pendingMessage.getStatus())) + throwableDesc;
        IMLog.logSendError(pendingMessage, MessageStatus.getTypeForLog(pendingMessage.getStatus()), IMException.getIMExceptionCode(throwable), desc);
    }
}
